#include "ConnectionDialog.h"

namespace SQLDoc
{
	ConnectionDialog::ConnectionDialog(QWidget* parent /*= 0*/, Qt::WFlags flags /*= 0*/ ) : QDialog(parent, flags)
	{
		setupUi(this);
		QObject::connect(m_driversComboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(drivers_currentIndexChanged(const QString&)));

		QStringList drivers = QSqlDatabase::drivers();

		m_driversComboBox->addItems(drivers);
		m_sqlEnginesComboBox->addItems(ODBCDriversList());

		m_sqlEnginesComboBox->setVisible(false);
		m_sqlEnginesLabel->setVisible(false);

		loadDialogSetting();
	}

	QString ConnectionDialog::driver()
	{
		return m_driversComboBox->currentText();
	}

	QString ConnectionDialog::sqlEngine()
	{
		return m_sqlEnginesComboBox->currentText();
	}

	QString ConnectionDialog::hostName()
	{
		return m_hostnameLineEdit->text();
	}

	QString ConnectionDialog::userName()
	{
		return m_userLineEdit->text();
	}

	QString ConnectionDialog::password()
	{
		return m_passwordLineEdit->text();
	}

	int ConnectionDialog::port()
	{
		return m_portSpinBox->value();
	}

	void ConnectionDialog::drivers_currentIndexChanged(const QString& text)
	{
		if (text.contains("QODBC"))
		{
			m_sqlEnginesComboBox->setVisible(true);
			m_sqlEnginesLabel->setVisible(true);
		}
		else
		{
			m_sqlEnginesComboBox->setVisible(false);
			m_sqlEnginesLabel->setVisible(false);
		}
	}

	QStringList ConnectionDialog::ODBCDriversList()
	{
		// TODO : Add platform sensitive list of available drivers
		QStringList list;
		list.push_back("SQL Server");
		list.push_back("MySQL ODBC 3.51 Driver");
		list.push_back("MySQL ODBC 5.1 Driver");

		return list;
	}

	void ConnectionDialog::loadDialogSetting()
	{
		int index = -1;
		int port = -1;
		QSettings setting;

		index = m_driversComboBox->findText(setting.value(AppSettings::LC_DRIVER).toString());
		if (index >= 0) m_driversComboBox->setCurrentIndex(index);

		index = m_sqlEnginesComboBox->findText(setting.value(AppSettings::LC_SQL_ENGINE).toString());
		if (index >= 0) m_sqlEnginesComboBox->setCurrentIndex(index);

		m_hostnameLineEdit->setText(setting.value(AppSettings::LC_HOSTNAME).toString());
		m_userLineEdit->setText(setting.value(AppSettings::LC_USERNAME).toString());
		m_passwordLineEdit->setText(setting.value(AppSettings::LC_PASSWORD).toString());

		port = setting.value(AppSettings::LC_PORT).toInt();
		if (port >= 0) m_portSpinBox->setValue(port);
		else m_portSpinBox->setValue(-1);
	}

	ConnectionDialog::~ConnectionDialog()
	{
		QSettings setting;
		setting.setValue(AppSettings::LC_DRIVER, m_driversComboBox->currentText());
		setting.setValue(AppSettings::LC_SQL_ENGINE, m_sqlEnginesComboBox->currentText());
		setting.setValue(AppSettings::LC_HOSTNAME, m_hostnameLineEdit->text());
		setting.setValue(AppSettings::LC_USERNAME, m_userLineEdit->text());
		setting.setValue(AppSettings::LC_PASSWORD, m_passwordLineEdit->text());
		setting.setValue(AppSettings::LC_PORT, m_portSpinBox->value());
	}
}
